<template>
  <div>
    <div class="warp">
      <div v-show="skuDataSetup[0]" style="margin-bottom: 20px;">
        <p class="type">批量折扣商品</p>
        <Table :columns="colData" :data="skuDataSetup"></Table>
      </div>
      <div v-if="skuDataPrice[0]" style="margin-bottom: 20px;">
        <p class="type">指定价格商品</p>
        <Table :columns="addColData" :data="skuDataPrice"></Table>
      </div>
      <div v-show="skuDataOnce[0]">
        <p class="type">一口价商品</p>
        <Table :columns="colData" :data="skuDataOnce"></Table>
      </div>
    </div>
    <Modal v-model="firstModal" @on-ok="changeCheck" title="单独设置价格体系">
      <RadioGroup v-model="setupRadio">
        <Radio label="1">sku商品批量折扣</Radio>
        <poptip placement="top" trigger="hover">
          <span style="margin-right: 8px;margin-top: 4px;cursor:pointer;">
            <Icon type="help-circled" color="#80848f" size="20"></Icon>
          </span>
          <div slot="content">
            <p>sku商品批量折扣：根据店铺的客户类型，sku商品价格可直接批量设置为相应客户类型的折扣后价格。</p>
            <p>例如：某商铺客户类型有“普通客户”、“vip客户”、“批发商客户”，且客户折扣已设置为“普通客户9折”、</p>
            <p>“vip客户6折”、“批发商客户3折”，那么当一款sku商品零售价为100元时，客户购买价经过该功能设置后，</p>
            <p>则普通客户购买价会自动设置为90元，vip客户购买价格会自动设置为60元，批发商客户购买价会自动设置为30元。</p>
          </div>
        </poptip>
        <Radio label="2">sku商品指定价格</Radio>
        <poptip placement="top" trigger="hover">
          <span style="margin-right: 8px;margin-top: 4px;cursor:pointer;">
            <Icon type="help-circled" color="#80848f" size="20"></Icon>
          </span>
          <div slot="content">
            <p>sku商品指定价格：针对某款sku商品，店铺根据客户类型的不同直接指定该款sku商品的不同销售价格。</p>
            <p>例如：某店铺客户类型有“普通客户”、“vip客户”、“批发商客户”，当一款sku商品零售价为100元时，经该功能设置，</p>
            <p>则可直接指定普通客户购买价格为90元，vip客户购买价格为60元，批发商客户购买价格为30元。</p>
          </div>
        </poptip>
        <Radio label="3">sku商品一口价</Radio>
        <poptip placement="top" trigger="hover">
          <span style="margin-right: 8px;margin-top: 4px;cursor:pointer;">
            <Icon type="help-circled" color="#80848f" size="20"></Icon>
          </span>
          <div slot="content">
            <p>sku商品一口价：针对某店铺的所有客户，都是统一的销售价格。</p>
          </div>
        </poptip>
      </RadioGroup>
    </Modal>
    <Modal v-model="showChangeInfo" @on-ok="subChangeInfo" title="修改商品信息">
      <Form :model="infoData" :label-width="70">
        <FormItem label="sku标题" prop="goodsSkuName">
          <Input v-model="infoData.goodsSkuName"/>
        </FormItem>
        <FormItem label="sku权重" prop="sortWeight">
          <Input v-model="infoData.sortWeight"/>
        </FormItem>
      </Form>
    </Modal>
    <image-util ref="imageUtil" @cropImg="cropImg" :fixed-number="[1, 1]"></image-util>
  </div>
</template>

<script>
import goodsImageUtil from './goodsImageUtil'
import imageUtil from '../../common/imageUtil'
export default {
  name: 'price-tab',
  data () {
    return {
      url: {
        priceUrl: '/discount/setup/manage/select/all/branch/customer',
        addSku: '/goods/manage/add/goods/sku/audit/page',
        removeSku: '/goods/manage/remove/goods/sku/audit/page',
        updateImg: '/goods/manage/modify/goods/sku/image/audit/page'
      },
      firstModal: false,
      setupRadio: '1',
      nowRow: {},
      colData: [
        {
          title: '图片',
          key: 'goodsSkuImagePath',
          width: 100,
          fixed: 'left',
          render: (h, params) => {
            let _self = this
            const baseUrl = 'https://hycos-1257620396.file.myqcloud.com'
            return h(goodsImageUtil, {
              props: {
                skuImg: baseUrl + params.row.goodsSkuImagePath,
                params
              },
              on: {
                setImage (e) {
                  _self.setImage(e)
                }
              }
            })
          }
        },
        {
          title: '名称',
          key: 'goodsSkuName',
          width: 100
        },
        {
          title: '货号',
          key: 'articleNumber',
          width: 60
        },
        {
          title: '排序',
          key: 'sortWeight',
          width: 60
        },
        {
          title: '库存类型',
          width: 190,
          render: (h, params) => {
            let _self = this
            const value = params.row.belong === '1' ? _self.firstPrice[params.index].skuStockType : (params.row.belong === '2' ? _self.secondPrice[params.index].skuStockType : _self.thirdPrice[params.index].skuStockType)
            return h('Select', {
              props: {
                value
              },
              on: {
                'on-change': (e) => {
                  if (params.row.belong === '1') {
                    _self.firstPrice[params.index].skuStockType = e
                  } else if (params.row.belong === '2') {
                    _self.secondPrice[params.index].skuStockType = e
                  } else if (params.row.belong === '3') {
                    _self.thirdPrice[params.index].skuStockType = e
                  }
                }
              }
            }, this.typeOfStock.map((item) => {
              return h('Option', {
                props: {
                  value: item.value
                }
              }, item.label)
            }))
          }
        },
        {
          title: '库存',
          key: 'stock',
          minWidth: 100,
          render: (h, params) => {
            let _self = this
            const value = params.row.belong === '1' ? _self.firstPrice[params.index].stock : (params.row.belong === '2' ? _self.secondPrice[params.index].stock : _self.thirdPrice[params.index].stock)
            return h('InputNumber', {
              props: {
                value: value,
                min: 0,
                max: 100000000
              },
              on: {
                input: (e) => {
                  if (params.row.belong === '1') {
                    _self.firstPrice[params.index].stock = e
                  } else if (params.row.belong === '2') {
                    _self.secondPrice[params.index].stock = e
                  } else if (params.row.belong === '3') {
                    _self.thirdPrice[params.index].stock = e
                  }
                }
              }
            })
          }
        },
        {
          title: '预警库存',
          key: 'warningStock',
          minWidth: 100,
          render: (h, params) => {
            let _self = this
            const value = params.row.belong === '1' ? _self.firstPrice[params.index].warningStock : (params.row.belong === '2' ? _self.secondPrice[params.index].warningStock : _self.thirdPrice[params.index].warningStock)
            return h('InputNumber', {
              props: {
                value: value,
                min: 0,
                max: 100000000
              },
              on: {
                input: (e) => {
                  if (params.row.belong === '1') {
                    _self.firstPrice[params.index].warningStock = e
                  } else if (params.row.belong === '2') {
                    _self.secondPrice[params.index].warningStock = e
                  } else if (params.row.belong === '3') {
                    _self.thirdPrice[params.index].warningStock = e
                  }
                }
              }
            })
          }
        },
        {
          title: '成本价',
          key: 'costPrice',
          minWidth: 120,
          render: (h, params) => {
            let _self = this
            const value = params.row.belong === '1' ? _self.firstPrice[params.index].costPrice : (params.row.belong === '2' ? _self.secondPrice[params.index].costPrice : _self.thirdPrice[params.index].costPrice)
            return h('div', [
              h('InputNumber', {
                props: {
                  value: value,
                  min: 0.01,
                  max: 100000000
                },
                style: {
                  float: 'left'
                },
                on: {
                  input: (e) => {
                    if (params.row.belong === '1') {
                      _self.firstPrice[params.index].costPrice = e
                    } else if (params.row.belong === '2') {
                      _self.secondPrice[params.index].costPrice = e
                    } else if (params.row.belong === '3') {
                      _self.thirdPrice[params.index].costPrice = e
                    }
                  }
                }
              })
            ])
          }
        },
        {
          title: '零售价',
          key: 'retailPrice',
          minWidth: 100,
          render: (h, params) => {
            let _self = this
            const value = params.row.belong === '1' ? _self.firstPrice[params.index].retailPrice : (params.row.belong === '2' ? _self.secondPrice[params.index].retailPrice : _self.thirdPrice[params.index].retailPrice)
            return h('InputNumber', {
              props: {
                value: value,
                min: 0.01,
                max: 100000000
              },
              on: {
                input: (e) => {
                  if (params.row.belong === '1') {
                    _self.firstPrice[params.index].retailPrice = e
                  } else if (params.row.belong === '2') {
                    _self.secondPrice[params.index].retailPrice = e
                  } else if (params.row.belong === '3') {
                    _self.thirdPrice[params.index].retailPrice = e
                  }
                }
              }
            })
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 220,
          fixed: 'right',
          render: (h, params) => {
            let _self = this
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  icon: 'gear-b'
                },
                style: {
                  marginRight: '8px'
                },
                on: {
                  click: () => {
                    _self.showChecked(params)
                  }
                }
              }, '设置'),
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '8px'
                },
                on: {
                  click: () => {
                    _self.changeInfo(params)
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small',
                  icon: 'close'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除商品',
                      content: '确定删除' + params.row.goodsSkuName + '吗？',
                      loading: true,
                      onOk: () => {
                        _self.removeSku(params.row)
                      }
                    })
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      // 价格体系
      skuDataSetup: [],
      // 具体价格
      skuDataPrice: [],
      // 一口价
      skuDataOnce: [],
      // 第一种价格
      firstPrice: [],
      // 第二种价格
      secondPrice: [],
      // 第三种价格
      thirdPrice: [],
      // 动态表头
      addColData: [],
      // sku图片更换
      changeImg: [],
      nowImgId: null,
      nowParams: {},
      typeOfStock: [
        {value: 1, label: '精准库存，不支持预定'},
        {value: 2, label: '精准库存，支持预定'},
        {value: 3, label: '无限量库存'}
      ],
      // 修改info
      infoData: {
        goodsSkuName: '',
        sortWeight: 0
      },
      showChangeInfo: false,
      isChange: false,
      priceTypeInfoDtos: []
    }
  },
  methods: {
    setColData (val) {
      if (val === '2') {
        this.skuDataPrice.push(...this.skuDataSetup, ...this.skuDataOnce)
        this.skuDataPrice.forEach(item => {
          item.belong = '2'
        })
        this.secondPrice.push(...this.firstPrice, ...this.thirdPrice)
        this.firstPrice = []
        this.thirdPrice = []
        this.skuDataSetup = []
        this.skuDataOnce = []
      } else if (val === '1') {
        this.skuDataSetup.push(...this.skuDataPrice, ...this.skuDataOnce)
        this.skuDataSetup.forEach(item => {
          item.belong = '1'
        })
        this.firstPrice.push(...(this.thirdPrice), ...(this.secondPrice))
        this.secondPrice = []
        this.thirdPrice = []
        this.skuDataPrice = []
        this.skuDataOnce = []
      } else if (val === '3') {
        this.skuDataOnce.push(...this.skuDataSetup, ...this.skuDataPrice)
        this.skuDataOnce.forEach(item => {
          item.belong = '3'
        })
        this.thirdPrice.push(...(this.firstPrice), ...(this.secondPrice))
        this.secondPrice = []
        this.firstPrice = []
        this.skuDataSetup = []
        this.skuDataPrice = []
      }
    },
    getPriceData () {
      let temp = []
      for (let i in this.priceTypeInfoDtos) {
        temp.push(this.priceTypeInfoDtos[i])
      }
      let params = {
        first: this.firstPrice,
        second: this.secondPrice,
        third: this.thirdPrice,
        priceTypeInfoDtos: temp
      }
      return JSON.parse(JSON.stringify(params))
    },
    // 修改标题。。。
    changeInfo (obj) {
      this.showChangeInfo = true
      this.nowRow = obj
      this.infoData.goodsSkuName = obj.row.goodsSkuName
      this.infoData.sortWeight = obj.row.sortWeight
    },
    subChangeInfo () {
      let params = {
        goodsSkuName: this.nowRow.row.goodsSkuName,
        sortWeight: this.nowRow.row.sortWeight
      }
      if (JSON.stringify(params) === JSON.stringify(this.infoData)) {
        return
      }
      let belong = this.nowRow.row.belong
      if (belong === '1') {
        this.setInfo(this.firstPrice, this.skuDataSetup)
      } else if (belong === '2') {
        this.setInfo(this.secondPrice, this.skuDataPrice)
      } else if (belong === '3') {
        this.setInfo(this.thirdPrice, this.skuDataOnce)
      }
    },
    setInfo (obj, data) {
      obj[this.nowRow.index].goodsSkuName = this.infoData.goodsSkuName
      obj[this.nowRow.index].sortWeight = this.infoData.sortWeight
      data[this.nowRow.index].sortWeight = this.infoData.sortWeight
      data[this.nowRow.index].goodsSkuName = this.infoData.goodsSkuName
      console.log(obj)
    },
    showChecked (obj) {
      this.nowRow = obj
      this.firstModal = true
    },
    pushChange (id, type) {
      if (this.priceTypeInfoDtos[id + 'P']) {
        this.priceTypeInfoDtos[id + 'P'].discountType = type
      } else {
        this.priceTypeInfoDtos[id + 'P'] = {
          skuId: id,
          discountType: type
        }
      }
    },
    changeCheck () {
      let change = this.isChange
      if (this.nowRow.row.belong === this.setupRadio) {
        return
      }
      if (this.nowRow.row.belong === '1') {
        let arrP = this.firstPrice.splice(this.nowRow.index, 1)
        if (this.setupRadio === '2') {
          let arr = this.skuDataSetup.splice(this.nowRow.index, 1)
          // console.log(arrP, arr)
          arr[0].belong = '2'
          this.secondPrice.push(arrP[0])
          this.skuDataPrice.push(arr[0])
          if (change) {
            this.pushChange(arr[0].goodsSkuId, 2)
          }
        } else if (this.setupRadio === '3') {
          let arr = this.skuDataSetup.splice(this.nowRow.index, 1)
          arr[0].belong = '3'
          this.thirdPrice.push(arrP[0])
          this.skuDataOnce.push(arr[0])
          if (change) {
            this.pushChange(arr[0].goodsSkuId, 3)
          }
        }
      } else if (this.nowRow.row.belong === '2') {
        let arrP = this.secondPrice.splice(this.nowRow.index, 1)
        if (this.setupRadio === '1') {
          let arr = this.skuDataPrice.splice(this.nowRow.index, 1)
          arr[0].belong = '1'
          this.firstPrice.push(arrP[0])
          this.skuDataSetup.push(arr[0])
          if (change) {
            this.pushChange(arr[0].goodsSkuId, 1)
          }
        } else if (this.setupRadio === '3') {
          let arr = this.skuDataPrice.splice(this.nowRow.index, 1)
          arr[0].belong = '3'
          this.thirdPrice.push(arrP[0])
          this.skuDataOnce.push(arr[0])
          if (change) {
            this.pushChange(arr[0].goodsSkuId, 3)
          }
        }
      } else if (this.nowRow.row.belong === '3') {
        let arrP = this.thirdPrice.splice(this.nowRow.index, 1)
        if (this.setupRadio === '1') {
          let arr = this.skuDataOnce.splice(this.nowRow.index, 1)
          arr[0].belong = '1'
          this.firstPrice.push(arrP[0])
          this.skuDataSetup.push(arr[0])
          if (change) {
            this.pushChange(arr[0].goodsSkuId, 1)
          }
        } else if (this.setupRadio === '2') {
          let arr = this.skuDataOnce.splice(this.nowRow.index, 1)
          arr[0].belong = '2'
          this.secondPrice.push(arrP[0])
          this.skuDataPrice.push(arr[0])
          if (change) {
            this.pushChange(arr[0].goodsSkuId, 2)
          }
        }
      }
    },
    setImage (e) {
      this.nowImgId = e.imgPath
      this.nowParams = e.params
      this.$refs.imageUtil.setImage(e)
    },
    cropImg (data) {
      let formData = new FormData()
      formData.append('skuImages', data.blob, 'file.jpg')
      let provideGoodsSkuImageDto = {
        goodsSkuId: data.name,
        skuImagePath: [this.nowImgId]
      }
      formData.append('provideGoodsSkuImageDto', JSON.stringify(provideGoodsSkuImageDto))
      this.$ajax.post(this.url.updateImg, formData).then(res => {
        if (this.nowParams.row.belong === '1') {
          this.skuDataSetup[this.nowParams.index].goodsSkuImagePath = res.data.data.skuImagePath
        } else if (this.nowParams.row.belong === '2') {
          this.skuDataPrice[this.nowParams.index].goodsSkuImagePath = res.data.data.skuImagePath
        } else if (this.nowParams.row.belong === '3') {
          this.skuDataOnce[this.nowParams.index].goodsSkuImagePath = res.data.data.skuImagePath
        }
        this.$Message.success('图片修改成功')
      })
    },
    getAddSku (data, id) {
      let formData = new FormData()
      let provideGoodsInfoAuditPageDto = {
        goodsSkuName: data.goodsSkuName,
        sortWeight: data.sortWeight,
        goodsId: id
      }
      formData.append('skuImage', data.imgBlob, 'file.jpg')
      formData.append('provideGoodsInfoAuditPageDto', JSON.stringify(provideGoodsInfoAuditPageDto))
      this.$ajax.post(this.url.addSku, formData, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
        if (res.data.success) {
          this.skuDataSetup.push({
            articleNumber: res.data.data.articleNumber,
            goodsSkuId: res.data.data.goodsSkuId,
            goodsSkuImagePath: res.data.data.skuImagePath,
            goodsSkuName: res.data.data.goodsSkuName,
            sortWeight: res.data.data.sortWeight,
            belong: '1'
          })
          this.firstPrice.push({
            id: res.data.data.goodsSkuId,
            stock: null,
            warningStock: null,
            costPrice: null,
            retailPrice: null,
            sortWeight: res.data.data.sortWeight,
            goodsSkuName: res.data.data.goodsSkuName
          })
          this.$Message.success('添加成功')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    removeSku (row) {
      let count = this.skuDataSetup.length + this.skuDataPrice.length + this.skuDataOnce.length
      if (count === 1) {
        this.$Notice.warning({
          title: '不可删除',
          desc: '必须要有一个SKU商品，可以添加一个之后删除当前SKU',
          duration: 0
        })
        this.$Modal.remove()
        return
      }
      let params = {
        goodsSkuId: row.goodsSkuId,
        skuImagePath: [row.goodsSkuImagePath]
      }
      this.$ajax.post(this.url.removeSku, JSON.stringify(params)).then(res => {
        if (res.data.success) {
          this.$Message.success('删除成功')
          this.$Modal.remove()
          if (row.belong === '1') {
            this.skuDataSetup.splice(row._index, 1)
            this.firstPrice.splice(row._index, 1)
          } else if (row.belong === '2') {
            this.skuDataPrice.splice(row._index, 1)
            this.secondPrice.splice(row._index, 1)
          } else if (row.belong === '3') {
            this.skuDataOnce.splice(row._index, 1)
            this.thirdPrice.splice(row._index, 1)
          }
        }
      }).catch(err => {
        console.log(err)
      })
    },
    initSkuData (data) {
      if (!data.isChange) {
        data.gsInfoEcho.forEach(item => {
          this.firstPrice.push({
            id: item.goodsSkuId,
            stock: null,
            warningStock: null,
            costPrice: null,
            retailPrice: null,
            sortWeight: item.sortWeight,
            goodsSkuName: item.goodsSkuName,
            skuStockType: 1
          })
        })
        this.skuDataSetup = data.gsInfoEcho
      } else {
        delete data.isChange
        for (let i in data) {
          this[i] = data[i]
        }
      }
    }
  },
  components: {
    goodsImageUtil,
    imageUtil
  },
  mounted () {
    this.$ajax.get(this.url.priceUrl).then(res => {
      let tempData = []
      res.data.data.forEach((item, index) => {
        tempData.push({
          title: item.name,
          key: 'price' + index,
          minWidth: 100,
          setupId: item.id,
          render: (h, params) => {
            let _self = this
            if (!_self.secondPrice[params.index].goodsPriceSetups) {
              _self.secondPrice[params.index].goodsPriceSetups = []
            }
            if (!_self.secondPrice[params.index].goodsPriceSetups[index]) {
              _self.secondPrice[params.index].goodsPriceSetups[index] = {
                goodsSkuId: params.row.goodsSkuId,
                branchCustomerId: item.id,
                price: null
              }
            }
            return h('InputNumber', {
              props: {
                value: _self.secondPrice[params.index].goodsPriceSetups[index].price,
                min: 0.01,
                max: 100000000
              },
              on: {
                input: (e) => {
                  _self.secondPrice[params.index].goodsPriceSetups[index].price = e
                }
              }
            })
          }
        })
      })
      let tempArr = [...this.colData]
      tempArr.push(...tempData)
      this.addColData = tempArr
    })
  },
  created () {
    if (this.$route.query.change) {
      this.isChange = true
    }
  }
}
</script>

<style scoped>
  .warp{
    margin-bottom: 18px;
  }
  .warp .type{
    border-top: 1px solid #ddd;
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    padding: 6px;
    font-size: 14px;
    font-weight: 700;
    color: #ed3f14;
  }
</style>
